package com.dd.stack.se.stream.io.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/8/21 12:01
 * @Description 类功能作用说明
 */
public class TCPClient {
    public static void main(String[] args) {
        String hostname = "localhost";
        int port = 8888;

        try (Socket socket = new Socket(hostname, port)) {
            // 获取输入输出流
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

            String userInput;
            System.out.println("请输入消息(输入bye结束):");
            // 读取用户输入并发送到服务器
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                // 打印服务器的回复
                System.out.println("服务器: " + in.readLine());

                // 如果输入"bye"，则退出
                if (userInput.equals("bye")) {
                    break;
                }
            }

            // 关闭资源
            out.close();
            in.close();
            stdIn.close();
        } catch (UnknownHostException e) {
            System.err.println("未知主机: " + hostname);
        } catch (IOException e) {
            System.err.println("无法连接到服务器: " + e.getMessage());
        }
    }
}